package com.bocloud.cmp.dao.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.bocloud.cmp.dao.BucketDao;
import com.bocloud.cmp.entity.resource.Bucket;
import com.bocloud.common.model.Param;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.MapTools;
import com.bocloud.database.core.intf.impl.JdbcGenericDao;
import com.bocloud.database.utils.SQLHelper;

/**
 * Bucket DAO接口实现
 * 
 * @author dongkai
 *
 */
@Repository("bucketDao")
public class BucketDaoImpl extends JdbcGenericDao<Bucket, Long> implements BucketDao {

	@Override
	public List<Bucket> list(int page, int rows, List<Param> params, Map<String, String> sorter) throws Exception {
		String sql = "select * from bucket v where v.is_deleted = 0";
		sql = SQLHelper.buildRawSql(sql, page, rows, params, sorter, "v");
		return this.list(Bucket.class, sql);
	}

	@Override
	public List<Bucket> listByVendorId(Long vendorId) throws Exception {
		String sql = "select * from bucket where is_deleted = 0 and vendor_id =:vendorId";
		Map<String, Object> params = MapTools.simpleMap("vendorId", vendorId);
		return this.list(Bucket.class, sql, params);
	}

	@Override
	public int count(List<Param> params) throws Exception {
		String sql = "select count(1) from bucket v where v.is_deleted = 0";
		sql = SQLHelper.buildRawSql(sql, params, null, "v");
		Map<String, Object> param = SQLHelper.getParam(params);
		return this.countQuery(sql, param).intValue();
	}

	@Override
	public boolean remove(Long id, Long userId) throws Exception {
		String sql = "update bucket set is_deleted = true,gmt_modify = :gmtModify,mender_id = :menderId where is_deleted = 0 and id = :id";
		Map<String, Object> params = MapTools.simpleMap("id", id);
		params.put("menderId", userId);
		params.put("gmtModify", new Date());
		return this.execute(sql, params) > 0;
	}

	@Override
	public Bucket query(Long id) throws Exception {
		String sql = "select * from bucket where is_deleted = 0 and id = :id";
		Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
		List<Bucket> list = this.list(Bucket.class, sql, params);
		if (list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public boolean removeByVid(Long vendorId, Long userId) throws Exception {
		String sql = "update bucket set is_deleted = 1, gmt_modify = :gmtModify, mender_id = :menderId where vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap("vendorId", vendorId);
		params.put("gmtModify", new Date());
		params.put("menderId", userId);
		return this.execute(sql, params) > 0;
	}

}
